package com.wrial.kind.linkedList;
/*
 * @Author  Wrial
 * @Date Created in 20:39 2020/8/7
 * @Description
 * 输入：(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 8 -> 0 -> 7
 */

import java.util.List;
import java.util.Stack;

public class AddTwoNumbers {

    /**
     * 因为这个顺序和平时计算是逆序  注意一定不要忘记处理carry  可以使用技巧，sum += s1.isEmpty() ? 0 : s1.pop();
     * 1.可以翻转链表
     * 2.可以使用栈（两个）
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode dummy = new ListNode(-1);
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();

        while (l1 != null) {
            s1.push(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            s2.push(l2.val);
            l2 = l2.next;
        }

        int carry = 0;
        while (!s1.isEmpty() || !s2.isEmpty() || carry > 0) {
            int sum = carry;
            sum += s1.isEmpty() ? 0 : s1.pop();
            sum += s2.isEmpty() ? 0 : s2.pop();
            carry = sum / 10;
            System.out.println(sum);

            ListNode node = new ListNode(sum % 10);
            node.next = dummy.next;
            dummy.next = node;

        }
        return dummy.next;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

}
